//
//  VehicleDetailViewController.m
//  Runone
//
//  Created by runone02 on 16/8/19.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "VehicleDetailViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "Define.h"
#import "RequestHelper.h"
#import "BDVehicleDetailInfo.h"
#import "CustomAnnotationView.h"
#import "ROPointAnnotation.h"
#import "AppDelegate.h"
#import "UUDatePicker.h"
#import "CameraGunDetailViewController.h"
#import "EnlargeMapViewController.h"
#import "UIView+Addition.h"
#import "CommonUtilityjudge.h"
#import "OneConst.h"

@interface VehicleDetailViewController ()<UITableViewDelegate, UITableViewDataSource,MAMapViewDelegate>

@property (nonatomic, strong) MAMapView *mapView; //地图

@property (nonatomic, strong) UITableView *vehicleInfoTableView;//

@property (strong, nonatomic)NSMutableArray *dataArray;

@property (strong, nonatomic)NSMutableArray *allPointAnnotationArray;

@property (strong, nonatomic) UIButton *cameraBtn;//摄像枪按钮

@property (nonatomic, assign) AllIconType type;
@end
@implementation VehicleDetailViewController {
    BDVehicleDetailInfo *vehicleDetailInfo;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadMapView]; //加载地图
    [self defaultAnnimation]; //设置到广乐路段
    [self configNavigationBar];
    [self requestData];  // 请求
    [self configView];
    [self showCameraGunArround2KM];//在地图上显示2000m内所有的摄像枪
    self.automaticallyAdjustsScrollViewInsets  = NO;
    self.view.backgroundColor=[UIColor whiteColor];
}

- (void) configNavigationBar {
    
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:(68.0 / 255) green:(169.0 / 255) blue:(213.0 / 255) alpha:1.000]];
    self.navigationController.navigationBar.tintColor=[UIColor whiteColor];
    
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.size     = CGSizeMake(100, 30);
    titleLabel.text     = _model.VehicleNo;
    titleLabel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = titleLabel;
}

- (void)configView {
    self.vehicleInfoTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 260, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStylePlain];
    self.vehicleInfoTableView.dataSource = self;
    self.vehicleInfoTableView.delegate   = self;
    self.vehicleInfoTableView.bounces    = NO;
    self.vehicleInfoTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:self.vehicleInfoTableView];
    //放大按钮
    UIButton *enlargeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [enlargeBtn setBackgroundImage:[UIImage imageNamed:@"btn_zoom_big"] forState:UIControlStateNormal];
    [enlargeBtn addTarget:self action:@selector(enlargeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    enlargeBtn.frame  =  CGRectMake(_mapView.bounds.size.width - 35 - 10, 74, 35, 35);
    [self.view addSubview:enlargeBtn];
    //路况
    UIButton *trafficBtn  = [UIButton buttonWithType:UIButtonTypeCustom];
    [trafficBtn setBackgroundImage:[UIImage imageNamed:@"路况图标1"] forState:UIControlStateNormal];
    [trafficBtn setBackgroundImage:[UIImage imageNamed:@"路况"] forState:UIControlStateSelected];
    [trafficBtn addTarget:self action:@selector(trafficBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    trafficBtn.frame = CGRectMake(_mapView.bounds.size.width - 35 - 10, 114, 35, 35);
    [self.view addSubview:trafficBtn];
}
- (void)enlargeBtnClick:(UIButton *)btn {
    EnlargeMapViewController *vc = [[EnlargeMapViewController alloc] init];
    vc.la = _model.Latitude;
    vc.lo = _model.Longitude;
    if ([_model.TransType isEqualToString:@"30"] || [_model.TransType isEqualToString:@"31"] || [_model.TransType isEqualToString:@"32"]) {
       _type = AllIconTypeDangerous;//危化品车图标
    }else {
       _type = AllIconTypeBus;// 客车图标
    }
    vc.type = _type;
    [self presentViewController:vc animated:YES completion:nil];
}
- (void)trafficBtnClick:(UIButton *)btn {
    NSLog(@"trafficeBtn");
    btn.selected = !btn.selected;
    if (btn.selected) {
        _mapView.showTraffic = YES;
    } else {
        _mapView.showTraffic = NO;
    }
}
- (void)loadMapView {
    [AMapServices sharedServices].apiKey = GETGAODEPAIKEY;
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,250)];
    _mapView.delegate     = self;
    _mapView.showsCompass = NO;
    _mapView.showsScale   = YES;
    _mapView.scaleOrigin  = CGPointMake(0, 210);
    [_mapView setZoomLevel:8];
    [self.view addSubview:_mapView];
}
-(void)defaultAnnimation {
    MACoordinateSpan span                   = MACoordinateSpanMake(0.027149, 0.052268);
    CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(self.model.Latitude, self.model.Longitude);
    MACoordinateRegion region               = MACoordinateRegionMake(centerCoordinate, span);
    _mapView.region                         = region;
}

- (void)requestData {
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *GetAllLastestVehicleDynamicModel=[[RequestGinsengModel alloc] init];
    GetAllLastestVehicleDynamicModel.URL         =  GetAllLastestVehicleDynamicURL;
    GetAllLastestVehicleDynamicModel.DataValue   =  [self DataValueVehicleNO:self.model.VehicleNo];
    GetAllLastestVehicleDynamicModel.UpdatedTime =  @"2012-01-12 12:00:00";
    GetAllLastestVehicleDynamicModel.SystemCode  =  @"GuangleHighway";
    GetAllLastestVehicleDynamicModel.MethodName  =  @"GetBDVehicleDetailInfo";
    requestHelper.block   = ^(RequestOutginseng *requestOutginseng,id  dataValueModel){
        vehicleDetailInfo = dataValueModel;
        [self.vehicleInfoTableView reloadData];
    };
    [requestHelper RequestGinsengModel:GetAllLastestVehicleDynamicModel andPushController:self];
}
#pragma mark -判断摄像枪是否在车辆为中心的2000m的半径内，并添加最近的摄像枪
- (void)showCameraGunArround2KM {
    MACircle *circle = [MACircle circleWithCenterCoordinate:CLLocationCoordinate2DMake(self.model.Latitude , self.model.Longitude) radius:2000];
    [_mapView addOverlay: circle];
    
    NSMutableArray *pointAnnotaionArray = [[NSMutableArray alloc] init];
    ROPointAnnotation *centerAnnotaion  = [[ROPointAnnotation alloc] init];
    centerAnnotaion.vehicleModel = self.model;
    centerAnnotaion.coordinate = CLLocationCoordinate2DMake(self.model.Latitude, self.model.Longitude);
    [pointAnnotaionArray addObject:centerAnnotaion];
    [_mapView addAnnotation:centerAnnotaion];
    
    AppDelegate *myDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate ;
    NSArray *dataSourceArray              = myDelegate.AllDeviceBaseArray ;
    NSMutableArray *tempDeviceArray       = [[NSMutableArray alloc] init];
    for (DeviceBaseInfo *model in dataSourceArray) {
        if (model.DeviceType == 4) {
            [tempDeviceArray addObject:model];
        }
    }
    NSMutableArray *containArray          = [[NSMutableArray alloc] init];
    for (DeviceBaseInfo *baseInfoModel in tempDeviceArray) {
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(baseInfoModel.Latitude, baseInfoModel.Longitude);
        BOOL isContain = MACircleContainsCoordinate(coordinate, CLLocationCoordinate2DMake(self.model.Latitude, self.model.Longitude), 2000);
        if (isContain) {
            [containArray addObject:baseInfoModel];
        }
    }
    NSMutableArray *array = [[NSMutableArray alloc] init];
    if (containArray.count == 0) {
        return;
    }else {
        [array addObject:containArray[0]];
    }
    NSMutableArray *numberArray = [[NSMutableArray alloc] init];
    MAMapPoint center = MAMapPointForCoordinate(CLLocationCoordinate2DMake(self.model.Latitude , self.model.Longitude));
    for (DeviceBaseInfo *model in array) {
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(model.Latitude, model.Longitude);
        MAMapPoint point                  = MAMapPointForCoordinate(coordinate);
        CLLocationDistance distance       = MAMetersBetweenMapPoints(point,center);
        NSNumber *number                  = [NSNumber numberWithDouble:distance];
        [numberArray addObject:number];
    }
    NSNumber *min                         = [numberArray valueForKeyPath:@"@min.doubleValue"];
    NSInteger index                       = [numberArray indexOfObject:min];
    DeviceBaseInfo *baseInfoModel         = containArray[index];
    // 摄像枪按钮
    UIButton *cameraBtn                 = [UIButton buttonWithType:UIButtonTypeCustom];
    cameraBtn.titleLabel.font = [UIFont systemFontOfSize:10];
    cameraBtn.tag             = index;
    cameraBtn.frame           = CGRectMake(self.view.bounds.size.width - 90, 220, 80, 30);
    [cameraBtn setBackgroundImage:[UIImage imageNamed:@"矢量智能对象-副本-2"] forState:UIControlStateNormal];
    [cameraBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -30)];
    [cameraBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    [cameraBtn setTitle:[NSString stringWithFormat:@"%@+%ld",baseInfoModel.PileNo,(long)baseInfoModel.PileDistance] forState:UIControlStateNormal];
    [cameraBtn addTarget:self action:@selector(cameraBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cameraBtn];
}
#pragma  mark - 跳转到摄像枪详情
- (void)cameraBtnClick {
    CameraGunDetailViewController *vc = [[CameraGunDetailViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = NO;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 7;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"cell";
    UITableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    switch (indexPath.row) {
        case 0:
            if (vehicleDetailInfo.VehicleNo == nil) {
                cell.textLabel.text = [NSString stringWithFormat:@"车辆号码:%@",_model.VehicleNo];
            }else {
                cell.textLabel.text = [NSString stringWithFormat:@"车辆号码:%@",vehicleDetailInfo.VehicleNo];
            }
            break;
        case 1:
            if (vehicleDetailInfo.VehicleType) {
                if (vehicleDetailInfo.VehicleType != 30 && vehicleDetailInfo.VehicleType != 31 && vehicleDetailInfo.VehicleType != 32 ) {
                    cell.textLabel.text  = [NSString stringWithFormat:@"车辆类型:危化品车辆"];
                }else {
                    cell.textLabel.text = [NSString stringWithFormat:@"车辆类型：营运客车"];
                }
            }else {
                cell.textLabel.text = @"车辆类型";
            }
            break;
        case 2:
            if (vehicleDetailInfo.GoodsType ) {
                cell.textLabel.text  = [NSString stringWithFormat:@"货物类型：%ld",(long)vehicleDetailInfo.GoodsType];
            }else {
                cell.textLabel.text = @"货物类型";
            }
            break;
        case 3:
            if (vehicleDetailInfo.Company) {
                cell.textLabel.text  = [NSString stringWithFormat:@"所属公司：%@",vehicleDetailInfo.Company];
            }else {
                cell.textLabel.text  = @"所属公司";
            }
            break;
        case 4:
            if (vehicleDetailInfo.Contactor) {
                cell.textLabel.text  = [NSString stringWithFormat:@"联系人：%@",vehicleDetailInfo.Contactor];
            }else {
                cell.textLabel.text = @"联系人";
            }
            break;
        case 5:
            if (vehicleDetailInfo.Contact) {
                cell.textLabel.text  = [NSString stringWithFormat:@"联系电话：%@",vehicleDetailInfo.Contact];
            }else {
                cell.textLabel.text = @"联系电话";
            }
            break;
        default:
            if (vehicleDetailInfo.Address) {
                cell.textLabel.text  = [NSString stringWithFormat:@"通讯地址：%@",vehicleDetailInfo.Address];
            }else {
                cell.textLabel.text = @"通讯地址";
            }
            break;
    }
    return cell;
}
#pragma mark -地图代理方法
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        CustomAnnotationView *annotationView   = (CustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil) {
            annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.selected              = NO;
        ROPointAnnotation *anno              = (ROPointAnnotation *)annotation;
        annotationView.vehicleModel          = anno.vehicleModel;
        annotationView.calloutView.backgroundColor = [UIColor clearColor];
        if ([annotationView.vehicleModel.TransType isEqualToString:@"30"] || [annotationView.vehicleModel.TransType isEqualToString:@"31"] || [annotationView.vehicleModel.TransType isEqualToString:@"32"]) {
            annotationView.image = [UIImage imageNamed:@"危险品车图标@3x.png"];//危化品车图标
        }else {
            annotationView.image = [UIImage imageNamed:@"营运车图标@3x.png"];// 客车图标
        }
        return annotationView;
    }
    return nil;
}
#pragma mark - 选中annotation时调用
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view {
    CustomAnnotationView *customView     = (CustomAnnotationView *)view;
    customView.selected                  = NO;//让车辆图标不能被选中
}
#pragma  mark - overlay 添加overlay
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay {
    if ([overlay isKindOfClass:[MACircle class]]){
        MACircleRenderer *circleRenderer = [[MACircleRenderer alloc]initWithCircle:overlay];
        circleRenderer.lineWidth = 5.f;
        circleRenderer.fillColor = [UIColor clearColor];
        circleRenderer.strokeColor = [UIColor clearColor];
        circleRenderer.lineWidth = 5.f;
        circleRenderer.lineDash = YES;
        
        return circleRenderer;
    }
    return nil;
}

- (NSString *)DataValueVehicleNO:(NSString *)VehicleNO  {
    NSString *valueStr =[NSString stringWithFormat:@"{\"key\":\"VehicleNo\",\"value\":\"%@\"}",VehicleNO];
    return valueStr;
}



@end
